package com.pires.keyspirit;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bean.FeedItem;
import bean.LoginUser;
import bean.LoginUserData;
import bean.TupaiUser;
import bean.UploadFile;
import network.NetworkRequest;
import network.TupaiSubscriber;
import rx.Subscription;
import rx.functions.Action1;
import rxbus.RxBus;
import utils.Constant;
import utils.SharedPreferenceUtil;
import utils.Utils;

import static rxbus.RxBus.RXBUS_DOWNLOAD_RESULT;
import static utils.Constant.IMAGE_SAVED_DIR;

public class MainActivity extends RxAppCompatActivity implements Handler.Callback {
    private Button mChangeBtn;
    private Handler mHandler = new Handler(this);

    private Subscription mSubscription;
    private Context mContext;

//    private String mNormalImagePath = "http://ototi15k5.bkt.clouddn.com/tupppai/20170803-015547-216a10bbf8fb96f0a7a40f7f98117680.jpg";
//    private String mSmallImagePath = "http://ototi15k5.bkt.clouddn.com/tupppai/20170803-015557-fec238792af84398b7fe52971c129a84.jpg";
//    private String mNoFaceImagePath = "http://ototi15k5.bkt.clouddn.com/tupppai/20170802-024427-2188028fb9788f541576025c51ab70b3.jpg";
//    private String mMultiFaceImagePath = "http://ototi15k5.bkt.clouddn.com/tupppai/20170803-020803-3a3518b41c6c3ec509f09485140f3caf.jpg";

//    private String mNormalImagePath = "http://ototi15k5.bkt.clouddn.com/tupppai/20170803-015557-fec238792af84398b7fe52971c129a84.jpg";
//    private String mSmallImagePath = "http://ototi15k5.bkt.clouddn.com/tupppai/20170803-015557-fec238792af84398b7fe52971c129a84.jpg";
//    private String mNoFaceImagePath = "http://ototi15k5.bkt.clouddn.com/tupppai/20170803-015557-fec238792af84398b7fe52971c129a84.jpg";
//    private String mMultiFaceImagePath = "http://ototi15k5.bkt.clouddn.com/tupppai/20170803-015557-fec238792af84398b7fe52971c129a84.jpg";

    private File mPathDir = new File(IMAGE_SAVED_DIR);

    private UploadManager mUploadManager;
    private String filePath;               // 上传图片的本地路径
    private List<Integer> mUploadIdList = new ArrayList<>();         // 上传多图返回的id
    private List<String> mTagList = new ArrayList<>();               // 选择的标题

    private List<FeedItem> mFeedList = new ArrayList<>();
    private List<LoginUserData> mLoginUserData = new ArrayList<>();       // 所有的用户信息

    private int mRequestPage = 2;
    private int mRequestSize = 1;
    private ColorDrawable colorDrawable;
//    private int mHasHandleCount = 0;       // 这次请求已经处理过的数字
//    private List<String> mImageList = new ArrayList<>();
//    private int mCurrentHandle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        mChangeBtn = (Button) findViewById(R.id.change_button);

        SharedPreferences sp = SharedPreferenceUtil.getSp();

        // 从sp中获取是否第一次启动数据,若无数据,默认为是1
        mRequestSize = sp.getInt(Constant.SPKey.REQUEST_SIZE, 100);

        initLoginUserData();
        initSubscription();
        initUpload();            // 初始化七牛上传
        LoginAndHandleImage();   // 马甲帐号登录，模拟点击处理图片

        Drawable background = mChangeBtn.getBackground();
        colorDrawable = (ColorDrawable) background;
        mChangeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (colorDrawable.getColor() == Color.parseColor("#00FF00")) {
                    mChangeBtn.setText("SpecialEffects");
                    mChangeBtn.setBackgroundColor(Color.parseColor("#FFFF00"));
                } else if (colorDrawable.getColor() == Color.parseColor("#FFFF00")) {

                    mChangeBtn.setText("");
                    mChangeBtn.setBackgroundColor(Color.parseColor("#FF0000"));

                    File[] childFile = mPathDir.listFiles();
                    if (childFile.length < 2) {
                        Toast.makeText(MainActivity.this, "存在异常", Toast.LENGTH_SHORT).show();
                        // 存在异常，文件夹下没有作品
                        RecursionDeleteFile(mPathDir);

                        mRequestSize++;    // 处理异常时，需要将请求的size+1

                        // 换一个马甲用户上传作品
                        LoginAndHandleImage();
                    } else {
                        Toast.makeText(MainActivity.this, "正常处理", Toast.LENGTH_SHORT).show();
                        // 上传处理后的图片
                        File file = childFile[childFile.length - 1];
                        mUploadIdList.clear();
                        getUploadToken("upload_" + file.getName(), file.getAbsolutePath());
                    }

                }
            }
        });
    }

    /**
     * 获取上传token
     */
    private void getUploadToken(String name, final String path) {
        NetworkRequest.getInstance().getUploadToken(name, MainActivity.this,
                new TupaiSubscriber<UploadFile>(mContext) {
                    @Override
                    protected void requestSuccess(UploadFile uploadFile) {
                        if (TextUtils.isEmpty(uploadFile.getToken())) {
                            return;
                        }
                        uploadToQiniu(uploadFile, path);
                    }

                    @Override
                    protected void requestError(String error) {
                        uploadError(error);
                    }
                });

    }

    /**
     * 上传到七牛
     */
    private void uploadToQiniu(final UploadFile uploadFile, String path) {
        mUploadManager.put(path, uploadFile.getKey(), uploadFile.getToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        if (info.isOK()) {
                            checkUpload(uploadFile.getUpload_id());
                        } else {
                            uploadError("info is no OK");
                        }
                    }
                }, null);
    }

    /**
     * 上传检查
     */
    private void checkUpload(final int upload_id) {
        NetworkRequest.getInstance().checkUpload(upload_id, this,
                new TupaiSubscriber<UploadFile>(mContext) {

                    @Override
                    protected void requestSuccess(UploadFile uploadFile) {
                        if (uploadFile != null) {
                            mUploadIdList.add(upload_id);
                            uploadImageData();
                        } else {
                            uploadError("upload == null");
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        uploadError(error);
                    }
                });
    }

    /**
     * 上传图片成功后,上传数据
     */
    private void uploadImageData() {
        String releasetype = "reply_ps";
        Map<String, String> locationMap = new HashMap<>();
        // 注意此时的parent_id已经加1了
        NetworkRequest.getInstance().uploadData(releasetype, "", mUploadIdList, mTagList, mFeedList.get(0).getId(), locationMap, this,
                new TupaiSubscriber<FeedItem>(getApplicationContext()) {
                    @Override
                    protected void requestSuccess(FeedItem jsonObject) {
                        if (jsonObject != null) {
                            Utils.showToast("上传成功");

                            // 换一个马甲用户上传作品
                            LoginAndHandleImage();
                            RecursionDeleteFile(mPathDir);
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        uploadError(error);
                    }
                });
    }

    /**
     * 上传失败
     */
    private void uploadError(String error) {
        Utils.showToast("上传失败:" + error);
    }

    @Override
    public boolean handleMessage(Message msg) {
        return false;
    }

    /**
     * 递归删除文件夹下的所有文件
     */
    public void RecursionDeleteFile(File file) {
        if (file.isFile()) {
            file.delete();
            updateGallery(file.getAbsolutePath());
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
//            if (childFile == null || childFile.length == 0) {
//                file.delete();
//                return;
//            }
            for (File f : childFile) {
                RecursionDeleteFile(f);
            }
            // 不删除文件夹
//            file.delete();
        }
    }

    // 通知媒体库更新文件  filename是我们的文件全名，包括后缀哦
    private void updateGallery(String filename)
    {
        MediaScannerConnection.scanFile(this,
                new String[]{filename}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });
    }

    /**
     * 模拟随机马甲用户登录
     */
    private void LoginAndHandleImage() {
        int range = (int) (Math.random()  * 4);
        LoginUserData loginUserData = mLoginUserData.get(range);
        NetworkRequest.getInstance().phoneLogin(loginUserData.userName, loginUserData.userPwd,
                new TupaiSubscriber<TupaiUser>(mContext) {
                    @Override
                    protected void requestSuccess(TupaiUser loginUser) {
                        LoginUser.getInstance().initFromResponse(loginUser);

                        // 获取没有作品的求P数据
                        GetNoReplyList();
                    }

                    @Override
                    protected void requestError(String error) {
                    }
                });
    }

    /**
     * 获取求P数据
     */
    private void GetNoReplyList() {
        NetworkRequest.getInstance().getNoReplyList(mRequestPage, mRequestSize,
                new TupaiSubscriber<List<FeedItem>>(mContext) {
                    @Override
                    protected void requestSuccess(List<FeedItem> feedItems) {
                        if (feedItems != null && feedItems.size() != 0) {
                            mFeedList.clear();
                            mFeedList.addAll(feedItems);
                        }

                        final String fileName = System.currentTimeMillis() + ".jpg";
                        filePath = IMAGE_SAVED_DIR + fileName;
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                DownloadUtil.saveImageToGallery(mFeedList.get(0).getMedias().get(0).getPathname(), fileName);
                            }
                        }, 2000);
                    }

                    @Override
                    protected void requestError(String error) {
                    }
                });
    }

    /**
     * 初始化上传
     */
    private void initUpload() {
        Configuration config = new Configuration.Builder()
                .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认256K
                .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认512K
                .connectTimeout(10) // 链接超时。默认10秒
                .responseTimeout(60) // 服务器响应超时。默认60秒
                .recorder(null)  // recorder分片上传时，已上传片记录器。默认null
                .recorder(null, null)  // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(Zone.httpsAutoZone) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();

        mUploadManager = new UploadManager(config);
    }

    /**
     * 初始化，监听器
     */
    private void initSubscription() {
        // 注册观察者
        mSubscription = RxBus.getInstance()
                .toObservable(RXBUS_DOWNLOAD_RESULT, String.class)
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mChangeBtn.setText("SpecialEffects");
                        mChangeBtn.setBackgroundColor(Color.parseColor("#00FF00"));

                        // 下载图片后，通知刷新文件系统
                        updateGallery(filePath);
                    }
                });
    }

    private void initLoginUserData() {
        LoginUserData loginUserData1 = new LoginUserData("tupppai", "12345678");
        LoginUserData loginUserData2 = new LoginUserData("sherry", "12345678");
        LoginUserData loginUserData3 = new LoginUserData("liuzi", "12345678");
        LoginUserData loginUserData4 = new LoginUserData("dayan", "12345678");
        LoginUserData loginUserData5 = new LoginUserData("majiapsda020", "12345678");

        mLoginUserData.add(loginUserData1);
        mLoginUserData.add(loginUserData2);
        mLoginUserData.add(loginUserData3);
        mLoginUserData.add(loginUserData4);
        mLoginUserData.add(loginUserData5);
    }

    @Override
    protected void onPause() {
        super.onPause();
        SharedPreferences.Editor editor = SharedPreferenceUtil.getEditor();
        editor.putInt(Constant.SPKey.REQUEST_SIZE, mRequestSize);
        editor.apply();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
